package com.woniu.zhoukao.controller;


import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.woniu.zhoukao.entity.User;
import com.woniu.zhoukao.service.CartService;
import com.woniu.zhoukao.service.UserService;
import com.woniu.zhoukao.utils.CookieUtils;
import com.woniu.zhoukao.utils.JwtUtils;
import com.woniu.zhoukao.vo.CartItemVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.util.List;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author liuao
 * @since 2023-02-07 09:47:30
 */
@Controller
@RequestMapping("/cart")
public class CartController {

    @Autowired
    CartService cartService;

    @Autowired
    UserService userService;

    @RequestMapping("add")
    @ResponseBody
    public String add(Integer productId, HttpServletRequest request){

        try {
            User currentUser = getCurrentUser(request);
            cartService.addProductToCart(productId, currentUser.getId());
        }catch (RuntimeException exception){
            exception.printStackTrace();
            return exception.getMessage();
        }

        return "ok";
    }


    private User getCurrentUser(HttpServletRequest request){
        //获取已登录用户信息
        // 1.先从request拿到token
        // 2.从token获取到用户名
        // 3.根据用户名查询到用户信息
        String userTokenFromCookie = CookieUtils.getUserTokenFromCookie(request);
        String account = JwtUtils.getAccountWithoutException(userTokenFromCookie);

        return userService.getUserByUserName(account);
    }


    @RequestMapping("all")
    @ResponseBody
    public List<CartItemVo> all(HttpServletRequest request){

        User currentUser = getCurrentUser(request);

        List<CartItemVo> cartItemVoList = cartService.queryAll(currentUser.getId());

        return cartItemVoList;
    }


    @RequestMapping("updateBuycount")
    @ResponseBody
    public String updateBuycount(Integer productId, Integer changeNum, HttpServletRequest request){

        try{
            User currentUser = getCurrentUser(request);

            cartService.updateBuycount(currentUser.getId(),productId,changeNum);
        }catch (Exception exception){
            exception.printStackTrace();
            return exception.getMessage();
        }

        return "ok";
    }


    @RequestMapping("calculateTotalPrice")
    @ResponseBody
    public BigDecimal calculateTotalPrice(@RequestParam("productIds[]") Integer[] productIds,HttpServletRequest request){

        User currentUser = getCurrentUser(request);
        BigDecimal totalPrice = cartService.calculateTotalPrice(currentUser.getId(), productIds);

        return totalPrice;
    }

    @GetMapping("toOrderPreview")
    public String toOrderPreview(Integer[] productIds, Model model) throws JsonProcessingException {

        //传给前端页面的时候,Java对象要转换为JSON字符串,才能在js中识别
        String productIdsJSON = new ObjectMapper().writeValueAsString(productIds);
        model.addAttribute("productIds",productIdsJSON);

        return "orderPreview";
    }

}



